import axios, { AxiosInstance, AxiosResponse } from "axios";
import errorHandle from "./errorHandle";
import { encode } from "js-base64";
const getTime = () => {
  const date = new Date();
  const Y = date.getFullYear();
  const M =
    date.getMonth() + 1 > 9 ? date.getMonth() + 1 : "0" + (date.getMonth() + 1);
  const D = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
  const H = date.getHours() > 9 ? date.getHours() : "0" + date.getHours();
  const m = date.getMinutes() > 9 ? date.getMinutes() : "0" + date.getMinutes();
  const s = date.getSeconds() > 9 ? date.getSeconds() : "0" + date.getSeconds();
  return `${Y}${M}${D}${H}${m}${s}`;
};
const getAuthorization = () => {
  const time = getTime();
  const a = "000000008a06c430018e653fa0fb00b2:" + time;
  console.log("time:", time);

  //   const b = md5(a).toString();
  //   console.log("getAuthorization：", b);

  //   return b.toUpperCase();
  return encode(a);
};
const axiosInstance: AxiosInstance = axios.create({
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json;charset=utf-8;",
    Authorization: getAuthorization(),
  },
});

// axios响应拦截
axiosInstance.interceptors.response.use(
  // 请求完成
  (response: AxiosResponse) => {
    if (response.status === 200) {
      return response.data;
    } else {
      // console.warn(response.status, errorHandle(response.status,response.message));
      return response;
    }
  },
  // 请求失败
  (error: any) => {
    const { response } = error;
    console.warn(
      response.status,
      errorHandle(response.status, response.message)
    );
    return Promise.reject(response);
  }
);

// axios请求拦截
axiosInstance.interceptors.request.use(
  // 请求完成
  (config: any) => {
    return config;
  },
  // 请求失败
  (error) => {
    return Promise.reject(error);
  }
);

export default axiosInstance;
